package com.cms.admin.action.privilege;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import net.sf.json.JSONObject;

import com.cms.admin.action.BaseAction;
import com.cms.admin.model.DepartmentList;
import com.cms.admin.model.FuncList;
import com.cms.admin.model.City;
import com.cms.admin.model.PageBean;
import com.cms.admin.model.UserRole;
import com.cms.admin.model.UserRoleExt;
import com.cms.admin.service.common.FuncListService;
import com.cms.admin.service.common.TemplateService;
import com.cms.admin.service.employee.DepartmentListService;
import com.cms.admin.service.privilege.CityService;
import com.cms.admin.service.privilege.UserRoleService;
import com.cms.admin.util.Constants;
import com.opensymphony.xwork2.ModelDriven;

public class RoleManagerAction extends BaseAction implements
		ModelDriven<UserRoleExt> {

	private UserRoleService roleService;
	private CityService orgService;

	private TemplateService templateService;
	private FuncListService menuService;

	private List<UserRole> roleList;
	private UserRole role;
	private String roleid;
	private UserRoleExt search = new UserRoleExt();
	private PageBean page;
	private String res;

	private DepartmentListService departmentService;
	
	private List<DepartmentList> departmentList;
	
 
 
 	//��ѡԪ��
 	private String allcolumns;
	
 	//��ѡԪ��
	private String selectedColumns;
	
	//�˵���
	List<FuncList>  tree =null;
	
	/**
	 * @return the selectedColumns
	 */
	public String getSelectedColumns() {
		return selectedColumns;
	}

	/**
	 * @param selectedColumns the selectedColumns to set
	 */
	public void setSelectedColumns(String selectedColumns) {
		this.selectedColumns = selectedColumns;
	}

	 
 
	public String preAddRole()
	{


		departmentList =departmentService.getAllRows();
		
		return SUCCESS;
	}
	
	public String ajaxQueryRole() {

		try {
			LOG.info("Start ArticleAction process,method is ajaxQuery");

			// ����ͨ��Ajax��param1=value���ַ�ʽ���ݵĲ����������ModelDriven�͵�search������
			search = getSearch();

			LOG.debug("Action is:" + search.getAction());
		 
			page = new PageBean(search.getCurrentPage(), search.getPageSize());

			roleList = roleService.getAllRoleByPage(page, search);
			departmentList =departmentService.getAllRows();
			tree =menuService.getAllMenu();
			// ҳ�棬��֯Ȩ�޷���
			//parseRoleResourceLable(roleList);

			String res = this.getQueryResult(roleList, departmentList,  tree, page);
			JSONObject o = new JSONObject();

			o.put("pageCount", page.getTotalPage());
			o.put("content", res);

			return ajaxJsonSuccessMessage(o);

		} catch (Exception e) {

			e.printStackTrace();
			return ajaxJsonErrorMessage(Constants.INFO_SYS_ERROR);
		}

	}

	private String getQueryResult(List<UserRole> roleList, List<DepartmentList> departmentList,List<FuncList>  tree,PageBean page)
			throws Exception {
		HashMap map = new HashMap();
		map.put("roleList", roleList);
		map.put("departmentList", departmentList);
		map.put("tree", tree);
		map.put("page", page);
		// System.out.println("��ҳ����"+page.getTotalPage());
		String result = "";
		result = templateService.generateContentByFreeMarker(
				Constants.TEMPLATE_ROLE_QUERY_RESULT, map);
		return result;
	}

	/***
	 * ҳ��չʾʱ��Ҫչʾ���ƣ�����id���з���
	 * @param roleList
	 */
	private void parseRoleResourceLable(List<UserRole> roleList) {
		long startTime=System.currentTimeMillis();
		LOG.info("��ʼ�����ɫ������ :" + startTime);
		
		for (UserRole r : roleList) {
/**
			// ����ҳ��Ȩ��
			if (null != r && null != r.getPages()) {
				String[] rolePagesArray = r.getPages().split("\\,");
				String rolePages = "";
				for (int i = 0; i < rolePagesArray.length; i++) {
					if (null != rolePagesArray[i]
							&& !"".equals(rolePagesArray[i])) {

						Menu menu = menuService.getByMenuId(rolePagesArray[i]);

						if (null != menu) {
							rolePages += menu.getLabel() + "|";
						}
					}

				}
				if (null != rolePages && rolePages.length() > 0)
					rolePages = rolePages.substring(0, rolePages.length() - 1);
				r.setPages(rolePages);
			}

			// �����֯��Ϊ�����
			if (null != r && null != r.getOrg()) {
				String[] roleOrgArray = r.getOrg().split("\\,");
				// System.out.println("�û���֯��"+roleOrgArray.toString());

				String roleOrg = "";
				for (int i = 0; i < roleOrgArray.length; i++) {

					if (null != roleOrgArray[i] && !"".equals(roleOrgArray[i])) {
						Organization org = orgService
								.selectByPrimaryKey(roleOrgArray[i]);

						if (null != org) {
							roleOrg += org.getName() + "|";
							;
						}
					}
				}
				if (null != roleOrg && roleOrg.length() > 0)
					roleOrg = roleOrg.substring(0, roleOrg.length() - 1);
				r.setOrg(roleOrg);
			}
			
			//�����ŵ�Ȩ��
			if (null != r && null != r.getResources()) {
					String[] roleResArray = r.getResources().split("\\,");
							 

							String roleRes = "";
							for (int i = 0; i < roleResArray.length; i++) {

								if (null != roleResArray[i] && !"".equals(roleResArray[i])) {
									
									Integer deptId = Integer.valueOf(roleResArray[i]);
									
									Department dept = departmentService.selectByPrimaryKey(deptId);

									if (null != dept) {
										roleRes += dept.getDeptName() + "|";
										;
									}
								}
							}
							if (null != roleRes && roleRes.length() > 0)
								roleRes = roleRes.substring(0, roleRes.length() - 1);
							r.setResources(roleRes);
						}
						**/
			
		}
		long endTime=System.currentTimeMillis();
		
		LOG.info("�����ɫ�����ݽ��� :" + endTime);
		LOG.info("�����ɫ�����ݻ���ʱ�� :" + (endTime-startTime)+"ms");
	}
	

	public String queryRoleList() {

		try {

			search = getSearch();

			page = new PageBean(search.getCurrentPage(), search.getPageSize());

			roleList = roleService.getAllRoleByPage(page, search);
			LOG.info("roleList size:" + roleList.size());
			 
			 
			departmentList =departmentService.getAllRows();
			tree =menuService.getAllMenu();
			// ҳ�棬��֯Ȩ�޷���
			//parseRoleResourceLable(roleList);

		    res = this.getQueryResult(roleList, departmentList,  tree, page);
		 	//res = getQueryResult(roleList, page);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return SUCCESS;
	}

	public String addRole() {
		
		 	
		LOG.info("Start RoleManagerAction process,method is addRole");
		//LOG.debug("role org:" + role.getOrg());
		//LOG.debug("role resources:" + role.getResources());

		
		roleService.insertRole(role);
		return SUCCESS;

	}

	public String getRoleById() {
		LOG.info("Start RoleManagerAction process,method is getRoleById");
		
		LOG.debug("Start RoleManagerAction process, RoleId is:"+roleid);
		 
		role = roleService.getRoleById(roleid);
		/*
		String department =role.getResources();
		List<Integer> deptNos= getDeptNos();
		departmentList =departmentService.getAllRows();
		
		StringBuffer option = new StringBuffer();
		
		for (DepartmentList tempDepartment : departmentList) 
		{
			
			
			String deptNo=String.valueOf(tempDepartment.getDeptNo());
			
			if(null!=deptNo && !"".equals(deptNo) && null!=department)
			{
				//�����ɫ���Ѵ��ڵ�ǰ���ź������ӵ���ѡ��Ԫ����
				//ע�����indexOf�����������ߵ�����һ�£�����������ź�ת��ΪString�����жϲ����Ƿ�������ַ�����
				if(department.indexOf(deptNo)<0)
				{   
					//System.out.println(deptNo);
					
					option.append("<option value=");
					option.append(tempDepartment.getDeptNo());
					option.append(">");
	              
					option.append(tempDepartment.getDeptLongName() != null ? tempDepartment.getDeptLongName(): "");
					option.append("</option>");
	              
					
				}
				
			}
			//�����ǰδ���ù���������Ҫ����ȫ������
			else if(null==department||"".equals(department))
			{
				option.append("<option value=");
				option.append(tempDepartment.getDeptNo());
				option.append(">");
              
				option.append(tempDepartment.getDeptLongName() != null ? tempDepartment.getDeptLongName(): "");
				option.append("</option>");
				
			}
			
			
		}
		
	    //��ѡԪ��
        allcolumns =option.toString();
        
        
        String[] tempDeptNo =null;
		//�����ﴦ�����б� selectedcolumns
        if(null!=department)
        {
        	tempDeptNo=department.split("\\,");
        }
		 
		StringBuffer selected = new StringBuffer();

	 
        String deptNo = null;
        
        if(null!=tempDeptNo && tempDeptNo.length>0)
        {
        	for (int i = 0; i < tempDeptNo.length; i++) 
            {

            		deptNo = tempDeptNo[i];
            	  
            	   if(null!=deptNo && !"".equals(deptNo))
            	   {
            		   DepartmentList de=  departmentService.selectByPrimaryKey(Integer.valueOf(deptNo));
            		   selected.append("<option value=");
            		   //selected.append(de.getDeptNo());
            		   selected.append(">");
                   
            		 //  selected.append(de.getDeptLongName() != null ? de.getDeptLongName(): "");
            		   selected.append("</option>");
                   

            		   //���һ�鲻������
            		   if (i < tempDeptNo.length - 1) {
            			    selected.append("");

            		   }
            		   
            	   }
            
               }
        	
        }
        
        
		
           

     
      
        	//��ѡԪ��
        selectedColumns =selected.toString();
       	 	*/
	 
		LOG.debug("RoleManagerAction  selectedColumns:"+selectedColumns);
		LOG.debug("RoleManagerAction  allcolumns:"+allcolumns);
		 
		return SUCCESS;
	}

	public String updateRoleById() {
		roleService.updateRole(role);
		return SUCCESS;
	}

	public String deleteRoleById() {
		roleService.deleteRole(roleid);
		return SUCCESS;
	}

	/**
	 * @return the roleService
	 */
	public UserRoleService getRoleService() {
		return roleService;
	}

	/**
	 * @param roleService
	 *            the roleService to set
	 */
	public void setRoleService(UserRoleService roleService) {
		this.roleService = roleService;
	}

	/**
	 * @return the roleList
	 */
	public List<UserRole> getRoleList() {
		return roleList;
	}

	/**
	 * @param roleList
	 *            the roleList to set
	 */
	public void setRoleList(List<UserRole> roleList) {
		this.roleList = roleList;
	}

	/**
	 * @return the role
	 */
	public UserRole getRole() {
		return role;
	}

	/**
	 * @param role
	 *            the role to set
	 */
	public void setRole(UserRole role) {
		this.role = role;
	}

	/**
	 * @return the roleid
	 */
	public String getRoleid() {
		return roleid;
	}

	/**
	 * @param roleid
	 *            the roleid to set
	 */
	public void setRoleid(String roleid) {
		this.roleid = roleid;
	}

	/**
	 * @return the orgService
	 */
	public CityService getOrgService() {
		return orgService;
	}

	/**
	 * @param orgService
	 *            the orgService to set
	 */
	public void setOrgService(CityService orgService) {
		this.orgService = orgService;
	}

	/**
	 * @return the menuService
	 */
	public FuncListService getMenuService() {
		return menuService;
	}

	/**
	 * @param menuService
	 *            the menuService to set
	 */
	public void setMenuService(FuncListService menuService) {
		this.menuService = menuService;
	}

	@Override
	public UserRoleExt getModel() {
		// TODO Auto-generated method stub
		return search;
	}

	/**
	 * @return the templateService
	 */
	public TemplateService getTemplateService() {
		return templateService;
	}

	/**
	 * @param templateService
	 *            the templateService to set
	 */
	public void setTemplateService(TemplateService templateService) {
		this.templateService = templateService;
	}

	/**
	 * @return the search
	 */
	public UserRoleExt getSearch() {
		return search;
	}

	/**
	 * @param search
	 *            the search to set
	 */
	public void setSearch(UserRoleExt search) {
		this.search = search;
	}

	/**
	 * @return the page
	 */
	public PageBean getPage() {
		return page;
	}

	/**
	 * @param page
	 *            the page to set
	 */
	public void setPage(PageBean page) {
		this.page = page;
	}

	/**
	 * @return the res
	 */
	public String getRes() {
		return res;
	}

	/**
	 * @param res
	 *            the res to set
	 */
	public void setRes(String res) {
		this.res = res;
	}
	
	/**
	 * @return the departmentService
	 */
	public DepartmentListService getDepartmentService() {
		return departmentService;
	}
	/**
	 * @param departmentService the departmentService to set
	 */
	public void setDepartmentService(DepartmentListService departmentService) {
		this.departmentService = departmentService;
	}
	/**
	 * @return the departmentList
	 */
	public List<DepartmentList> getDepartmentList() {
		return departmentList;
	}
	/**
	 * @param departmentList the departmentList to set
	 */
	public void setDepartmentList(List<DepartmentList> departmentList) {
		this.departmentList = departmentList;
	}

	/**
	 * @return the allcolumns
	 */
	public String getAllcolumns() {
		return allcolumns;
	}

	/**
	 * @param allcolumns the allcolumns to set
	 */
	public void setAllcolumns(String allcolumns) {
		this.allcolumns = allcolumns;
	}

	 

	
}
